package com.spmsys.util;

import org.jetbrains.annotations.NotNull;

import java.io.*;

/**
 * json文件操作类
 */
public class JSONFileOperate {

    /**
     * 读取json文件方法
     *
     * @param filePath 文件路径
     * @return json字符串
     */
    public static @NotNull String readJson(String filePath) {
        File jsonFile = new File(filePath);
        //如果文件不存在则抛出异常
        if (!jsonFile.exists()) {
            throw new RuntimeException("文件" + filePath + "不存在");
        }
        try (FileReader fileReader = new FileReader(jsonFile); BufferedReader bufferedReader = new BufferedReader(fileReader)) {
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            //读取文件
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            //返回数据
            return stringBuilder.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 写入json文件方法
     *
     * @param filePath 文件路径
     * @param json     json字符串
     * @param append   是否追加
     */
    public static void writeJson(String filePath, String json, Boolean append) {
        File file = new File(filePath);
        try {
            //如果文件不存在则创建文件，创建失败则抛出异常
            if (!file.exists() && !file.createNewFile()) {
                throw new RuntimeException(filePath + "文件创建失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try (FileWriter fileWriter = new FileWriter(file.getAbsoluteFile(), append); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            //写入文件
            bufferedWriter.write(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
